package com.grid.control;

import com.grid.entity.Mission;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.text.Text;
import javafx.stage.Stage;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;

public class GridMissionViewController implements Initializable {

    @FXML private Text SumMission;
    @FXML private Text WaitingMission;
    @FXML private Text DoneMission;
    @FXML private TableColumn<Mission, String> reporterColumn;
    @FXML private TableColumn<Mission, String> phoneColumn;
    @FXML private TableColumn<Mission, String> gridColumn;
    @FXML private TableColumn<Mission, String> locationColumn;
    @FXML private TableColumn<Mission, String> levelColumn;
    @FXML private TableColumn<Mission, String> descriptionColumn;
    @FXML private TableColumn<Mission, Void> actionColumn;

    @FXML private TableView<Mission> table;

    private final ObservableList<Mission> missionData = FXCollections.observableArrayList();

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        setupTableColumns();
        loadMissionsFromFile();
        addActionButtonToTable();
    }

    private void setupTableColumns() {
        reporterColumn.setCellValueFactory(new PropertyValueFactory<>("reporter"));
        phoneColumn.setCellValueFactory(new PropertyValueFactory<>("phone"));
        gridColumn.setCellValueFactory(new PropertyValueFactory<>("grid"));
        locationColumn.setCellValueFactory(new PropertyValueFactory<>("location"));
        levelColumn.setCellValueFactory(new PropertyValueFactory<>("level"));
        descriptionColumn.setCellValueFactory(new PropertyValueFactory<>("description"));
    }

    private void loadMissionsFromFile() {
        File file = new File("mission.txt");

        if (!file.exists()) {
            System.err.println("任务文件 mission.txt 不存在");
            return;
        }

        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] parts = line.split(",");
                if (parts.length == 9) {
                    missionData.add(new Mission(
                            parts[0].trim(),
                            parts[1].trim(),
                            parts[2].trim(),
                            parts[3].trim(),
                            parts[4].trim(),
                            parts[5].trim(),
                            parts[6].trim(),
                            parts[7].trim(),
                            parts[8].trim()
                    ));
                }
            }
            table.setItems(missionData);
        } catch (IOException e) {
            System.err.println("读取任务文件失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    private void addActionButtonToTable() {
        actionColumn.setCellFactory(param -> new TableCell<>() {
            private final Button btn = new Button("处理任务");

            {
                btn.setOnAction(event -> {
                    Mission mission = getTableView().getItems().get(getIndex());
                    try {
                        openMissionSubmitView(mission);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });
            }

            @Override
            protected void updateItem(Void item, boolean empty) {
                super.updateItem(item, empty);
                setGraphic(empty ? null : btn);
            }
        });
    }

    private void openMissionSubmitView(Mission mission) throws IOException {
        FXMLLoader loader = new FXMLLoader(getClass().getResource("/com/admin/view/MissionSubmitView.fxml"));
        Parent root = loader.load();

        MissionSubmitViewController controller = loader.getController();
        controller.initData(mission);

        SumMission.setText("3");
        WaitingMission.setText("3");
        DoneMission.setText("0");
        Stage stage = new Stage();
        stage.setScene(new Scene(root));
        stage.setTitle("任务处理");
        stage.show();
    }
}